<template>


<el-button type="primary"  @click="handleAdd">
   新增用户
  </el-button>


<el-table :data="tableData" style="width: 100%">
    <el-table-column label="账号" prop="userName" />
    <el-table-column label="昵称" prop="nickName" />
    <el-table-column label="邮箱" prop="email" />
    <el-table-column label="备注" prop="remark" />
    <el-table-column label="创建时间" prop="createTime" />
    <el-table-column align="right">
      <template #header>
    <el-input v-model="queryForm.query"  @input="initUserList" placeholder="请输入内容"></el-input>
      </template>
      <template #default="scope">
        <el-button size="small"  type="primary" @click="handleEdit(scope.$index, scope.row)">
          编辑
        </el-button>
        <el-button
          size="small"
          type="primary"
          @click="handleDelete(scope.$index, scope.row)" >
          分配角色
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
      v-model:current-page="queryForm.pageNum"
      v-model:page-size="queryForm.pageSize"
      :page-sizes="[10, 20, 30, 40]"
      :size="size"

      background layout="prev, pager, next"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"/>

    <el-dialog v-model="dialogFormVisible" title="新增用户" width="500">
      <el-form :model="userFrom" :rules="rules" ref="formRef" label-width="auto" style="max-width: 600px">
    <el-form-item prop="userName" label="用户名">
      <el-input v-model="userFrom.userName" :disabled="userFrom.userId?true:false" placeholder="请输入用户名"></el-input>
    </el-form-item>
    <el-form-item prop="password" label="密码">
      <el-input type="password" v-model="userFrom.password" placeholder="请输入密码"></el-input>
    </el-form-item>
    <el-form-item label="手机号码" prop="phonenumber" >
        <el-input v-model="userFrom.phonenumber"  placeholder="请输入手机号码" />
      </el-form-item>
    <el-form-item label="用户昵称" prop="nickName" >
        <el-input v-model="userFrom.nickName" placeholder="请输入用户昵称"/>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email" >
        <el-input v-model="userFrom.email"  placeholder="请输入用户邮箱"/>
      </el-form-item>
      <el-form-item label="备注" prop="remark" >
        <div style="margin: 20px 0" />
        <el-input v-model="userFrom.remark"  placeholder="请输入备注"/>
      </el-form-item>
   
  </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="resetForm">取消</el-button>
        <el-button type="primary" @click=" submitForm()">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>



  <el-dialog v-model="roleConfigFormVisible" title="角色配置" width="1000">
            <el-row >
                <el-col :span="12">
                    <el-table :data="sourceMenu" style="width: 50%">
                            <el-table-column label="角色" width="180" prop="roleName" />
                            <el-table-column align="right">
                            <template #default="scope">
                                <el-button size="small"  type="primary" @click="addConfig(scope.$index, scope.row)">
                                   添加角色配置
                                </el-button>
                            </template>
                            </el-table-column>
                      </el-table>
                </el-col>
                <el-col :span="12">
                    <el-table :data="configMenu" style="width:50%">
                            <el-table-column label="已配置角色" width="180" prop="roleName" />
                            <el-table-column align="right">
                            <template #default="scope">
                                <el-button size="small"  type="primary" @click="unConfig(scope.$index, scope.row)">
                                   取消角色配置
                                </el-button>
                            </template>
                            </el-table-column>
                    </el-table>
                </el-col>
            </el-row>
            <template #footer>
          <div class="dialog-footer">
            <el-button @click="roleConfigFormVisible=false">取消</el-button>
            <el-button type="primary" @click=" submitMenuConfig()">
              确认配置
            </el-button>
          </div>
        </template>
      </el-dialog>




</template>

<script  setup>
     import {ref,reactive} from 'vue';
     import request from '@/util/request';
     import { ElMessage } from 'element-plus'
     const sourceMenu=ref([]);
    const configMenu=ref([]);
    const userId=ref('');
    const roleConfigFormVisible = ref(false)
     const dialogFormVisible = ref(false)
     const tableData=ref([]);
     const total=ref(0);
     const queryForm=ref({
        query:"",
        pageNum:1,
        pageSize:10
     })
     const initUserList=async ()=>{
       const res= await request.post("/user/list",queryForm.value)
       tableData.value=res.data.data.userList;
       total.value=res.data.data.total;
     }
     initUserList();
     const handleSizeChange=(pageSize)=>{
        queryForm.value.pageNum=1;
        queryForm.value.pageSize=pageSize
        initUserList();
     }
     const handleCurrentChange=(pageNum)=>{
        queryForm.value.pageNum=pageNum;
         
        initUserList();
     }
 
     const userFrom = reactive({
      userId:'',
      userName: '',
      password: '',
      nickName: '',
      email: '',
      phonenumber: '',
      remark:''
})

const formRef = ref(null);


const validateUsername = (rule, value, callback) => {
  if (value.length < 3) {
    callback(new Error('用户名长度不能小于3位'));
  } else {
    callback();
  }
};
 
const validatePassword = (rule, value, callback) => {
  if (value.length < 6) {
    callback(new Error('密码长度不能小于6位'));
  } else {
    callback();
  }
};
 
const rules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur',whitespace: true  },
    { validator: validateUsername, trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ],
  phonenumber: [
            { required: true, message: '请输入手机号', trigger: 'blur' },
            { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
          ],
  email: [
            { required: true, message: '请输入邮箱地址', trigger: 'blur' },
            { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
          ],
};
 
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      request.post("user/saveOrUpdate",userFrom).then(res=>{
       if(res.data.code==200){
        initUserList();
        dialogFormVisible.value = false
        ElMessage.success("新增成功")
       }else{
        ElMessage.error(res.data.msg);
       }
      })
    } else {
      return false;
    }
  });
};
const handleEdit=(index,row)=>{
 let userInfo=  Object.assign({}, row)
  userFrom.userId=userInfo.userId;
  userFrom.userName=userInfo.userName;
  userFrom.password=userInfo.password;
  userFrom.nickName=userInfo.nickName;
  userFrom.email=userInfo.email;
  userFrom.phonenumber=userInfo.phonenumber;
  userFrom.remark=userInfo.remark;
  dialogFormVisible.value = true
}

const handleAdd=()=>{
  userFrom.userId="";
  dialogFormVisible.value = true
}

const resetForm = () => {
  userFrom.userId='';
  userFrom.userName='';
  userFrom.password='';
  userFrom.nickName='';
  userFrom.email='';
  userFrom.phonenumber='';
  userFrom.remark='';
      dialogFormVisible.value = false
    }

    const handleDelete =(index,row)=>{
     let obj=  Object.assign({}, row)
     userId.value=obj.userId ;
     request.get("user/getRoleByUserId/"+obj.userId ).then(res=>{
           if(res.data.code==200){
             let dataMap= res.data.data;
             sourceMenu.value = dataMap.notRole;
             configMenu.value = dataMap.inRole;
             roleConfigFormVisible.value = true
           }else{
            ElMessage.error(res.data.msg);
           }
          })
    }



    const  addConfig = (index,row)=>{
      let item=  sourceMenu.value[index];
      configMenu.value.push(item)
      sourceMenu.value.splice(index, 1);
    }
    const  unConfig = (index,row)=>{
      let item=  configMenu.value[index];
      sourceMenu.value.push(item)
      configMenu.value.splice(index, 1);
    }

    const userRole = reactive({
      userId:userId,userRole:configMenu
    })
    const submitMenuConfig =()=>{
        request.post("user/addRole",userRole).then(res=>{
           if(res.data.code==200){
            roleConfigFormVisible.value = false
            ElMessage.success("新增成功")
           }else{
            ElMessage.error(res.data.msg);
           }
          })

    }


 
</script>

<style lang="scss" scoped>

</style>
